<template>
    <div class="main" style="font-size: 12px;">
        <div class="header">
            <div class="search">

                <el-input style="width: 300px;" size='small' placeholder="请输入变更单名" v-model="params.name">
                    <template slot="prepend">名称</template>
                </el-input>
                <el-select v-model="params.warehouseId" size='small' style='margin: 0 20px;' placeholder="请选择仓库">
                    <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                        :value="item.warehouseId">
                    </el-option>
                </el-select>
                <el-select v-model="params.changeTypeId" size='small' style='margin: 0 20px;' placeholder="请选择变更类型">
                    <el-option v-for="item in changeTypeList" :key="item.id" :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
                <el-date-picker v-model="params.time" size='small' type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" @change="chooseTime">
                </el-date-picker>
                <el-button @click="searchGetChangeList" size='small'
                    style='background-color: #ff6a00;color:white;margin-left:20px'>查询</el-button>
            </div>
            <div>
                <el-button size='small' style='background-color: #ff6a00;color:white' @click="addChange">新增</el-button>
            </div>
        </div>
        <!-- 盘点表   -->
        <div class="mainTable">
            <el-table style="font-size: 12px;width: 100%;" :height="maxHeight + 'px'" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                v-loading="loading" :data="changeList.list" border
                :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', 'background': '#ff6a00', 'color': 'white' }"
                :cellStyle="{ 'textAlign': 'center','fontSize': '12px' }">
                <el-table-column prop="changeId" label="变更单号" min-width="140px"></el-table-column>
                <el-table-column prop="changeName" label="单名" min-width="140px"></el-table-column>
                <el-table-column prop="warehouse.warehouseName" min-width="100px" label="仓库"></el-table-column>
                <el-table-column label="类型">
                    <template slot-scope="props">
                        <el-link v-if="props.row.changeType == 1">销售</el-link>
                        <el-link v-if="props.row.changeType == 2 ">采购 </el-link>
                        <el-link v-if="props.row.changeType == 3">盘点</el-link>
                        <el-link v-if="props.row.changeType == 4">损坏</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="targetId" label="关联单号"></el-table-column>
                <el-table-column label="明细" width="600px">
                    <template slot-scope="props">
                        <el-table :data="props.row.changeDetailList" border maxHeight="300px"
                            :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', }"
                            :cellStyle="{ 'textAlign': 'center' ,'fontSize': '12px'}">
                            >
                            <el-table-column prop="materialId" min-width="100" label="材料编码"></el-table-column>
                            <el-table-column prop="materialName" min-width="150" label="材料名称"></el-table-column>
                            <el-table-column prop="price" min-width="80" label="成本价"></el-table-column>
                            <el-table-column min-width="80" label="数量">
                                <template slot-scope="props">
                                    <el-link :type="props.row.count < 0 ? 'danger' : 'success'">{{ props.row.count
                                        }}</el-link>
                                </template>
                            </el-table-column>
                            <el-table-column prop="totalPrice" width="100" label="价格"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column prop="sumXPrice" label="价格总计" width="100"></el-table-column>
                <el-table-column label="状态" width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.changeStatus == 0" type="danger" size="mini">待处理</el-tag>
                        <el-tag size="mini" v-if="scope.row.changeStatus == 1" type="success">已通过</el-tag>
                        <el-tag size="mini" v-if="scope.row.changeStatus == 2" type="info">已驳回</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="reason" label="原因" width="200"></el-table-column>
                <el-table-column prop="remark" label="备注" width="200"></el-table-column>
                <el-table-column prop="changeTime" label="变更日期" width="120"></el-table-column>
                <el-table-column fixed="right" label="操作" width="220" v-if="userName == 'admin' ||userName=='王伯维'||userName=='沈旭滨'||userName=='王健'||userName=='袁文典'">
                    <template slot-scope="data">
                        <el-button size="mini" @click="updateStatus(true, data.row)">通过</el-button>
                        <el-button size="mini" type="danger" @click="updateStatus(false, data.row)">驳回</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style='margin-top:20px' align="right" @size-change="handleChangeSizeChange"
                @current-change="handleChangeCurrentChange" :current-page="changeList.currentPage"
                :page-sizes="[20,30,40,50]"  layout="total, sizes, prev, pager, next, jumper"
                :total="changeList.count">
            </el-pagination>
        </div>
        <!-- 新增 -->
        <el-dialog title="新增库存变更单" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
            <div style="" class="createInfo">
                <div>
                    <div>名称</div>
                    <el-input placeholder="请输入变更单名" v-model="createdInfo.name" clearable>

                    </el-input>
                </div>
                <div>
                    <div>
                        仓库
                    </div>
                    <el-select v-model="createdInfo.warehouseId" clearable style='width: 100%;' placeholder="请选择仓库">
                        <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                            :value="item.warehouseId">
                        </el-option>
                    </el-select>
                </div>
                <div>
                    <div>
                        类型
                    </div>
                    <el-select v-model="createdInfo.changeTypeId" clearable style='width: 100%;' @change='typeChange'
                        placeholder="请选择变更类型">
                        <el-option v-for="item in changeTypeList" :key="item.value" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div>
                    <div>
                        订单号
                    </div>
                    <el-select filterable v-model="createdInfo.orderId" clearable style='width: 100%;' placeholder="请选择目标单号">
                        <el-option v-if="createdInfo.changeTypeId == 1" v-for="item in orderList" :key="item.saleId" :label="`名称:${item.storeName} - 单号:${item.saleId}`" :value="item.saleId">
                        </el-option>
                        <el-option v-if="createdInfo.changeTypeId == 2" v-for="item in orderList" :key="item.procureId"  :label="`名称:${item.orderName} - 单号: ${item.procureId}`"  :value="item.procureId">
                        </el-option>
                        <el-option v-if="createdInfo.changeTypeId == 3" v-for="item in orderList" :key="item.checkId" :label="`名称:${item.checkName} - 单号: ${item.checkId}`"  :value="item.checkId">
                        </el-option>
                        <el-option v-if="createdInfo.changeTypeId == 4" v-for="item in orderList" :key="item.value" :label="`名称:${item.chcekName} - 单号: ${item.checkId}`" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div>
                    <div>变更日期</div>
                    <el-date-picker style="width: 100%;" v-model="createdInfo.time" type="date" placeholder="选择日期">
                    </el-date-picker>
                </div>
                <div>
                    <div>原因
                    </div>
                    <el-input placeholder="请输入变更原因" v-model="createdInfo.reason" clearable>

                    </el-input>
                </div>
                <div>
                    <div>备注</div>
                    <el-input placeholder="请输入备注" rows='8' type="textarea" v-model="createdInfo.remark">

                    </el-input>
                </div>
                <div>
                    <div>凭证</div>
                    <div>
                        <rayUpload @url="getImageUrl"></rayUpload>
                    </div>
                </div>
            </div>
            <div style="margin-top: 20px;">
                <div style='margin-bottom: 10px'><span style="color:red;">*</span>请选择先选择变更仓库</div>
                <el-table :height="300" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                    v-loading="loading" :data="materialList" border style="width: 100%"
                    :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', 'background': '#ff6a00', 'color': 'white' }"
                    :cellStyle="{ 'textAlign': 'center' ,'fontSize': '12px'}">

                    <el-table-column prop="materialId" label="材料编码" min-width="120"></el-table-column>
                    <el-table-column prop="material.materialName" label="材料名称" min-width="280"></el-table-column>
                    <el-table-column prop="material.norm" label="规格" min-width="120"></el-table-column>
                    <el-table-column prop="material.color" label="颜色" min-width="100"></el-table-column>
                    <el-table-column prop="material.unit" label="单位" min-width="100"></el-table-column>
                    <el-table-column prop="material.price" label="成本价" min-width="100"></el-table-column>
                    <el-table-column prop="material.salePrice" label="销售价" min-width="100"></el-table-column>
                    <el-table-column label="数量" min-width="200">
                        <template slot-scope="scope">
                            <el-input-number size='mini' v-model.trim="scope.row.count"></el-input-number>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="addChangeConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import dayjs from "dayjs";
import Decimal from "decimal.js";

import tableMixins from "@/mixins/tableMixins.vue";
import rayUpload from '@/RayComponents/rayUpload.vue'

import quinn from "@/utils/quinn";

export default {
    name: "inventorychanges",
    mixins: [tableMixins],
    meta: { title: "库存变更", icon: "el-icon-box", sort: 15 ,authority: 112},
    components: {
        rayUpload
    },
    data() {
        return {
            apiName: "classificationMaterialList",
            loading: false,
            warehouseList: [],
            dialogVisible: false,
            userName: '',
            params: {
                name: '',
                startTime: '',
                endTime: '',
                warehouseId: '',
                changeTypeId:''
            },
            createdInfo: {
                time: '',
                warehouseId: '',
                name: '',
                remark: '',
                reason: '',
                changeInVouchers: '',
                changeTypeId: '',
                orderId: '',//变更订单ID
            },
            changeTypeList: [
                { 'name': '销售订单', 'id': 1 },
                { 'name': '采购订单', 'id': 2 },
                { 'name': '盘点记录', 'id': 3 },
                { 'name': '损失记录', 'id': 4 }
            ],
            changeList: {
                list: [],
                count: 100,
                currentPage: 1,
                pageSize: 20,
                pageNumber: 1
            },
            materialList: [],
            maxHeight: 0,

            orderList: []
        };
    },
    mounted() {
        this.userName = quinn.getStorage("userDatav3").userName
        this.$nextTick(() => {
            this.maxHeight = window.innerHeight - 240;
        })
        window.onresize = () => {
            this.$nextTick(() => {
                this.maxHeight = window.innerHeight - 240;
            })
        }
    },
    watch: {
        "$store.state.warehouseList": {
            handler(newVal) {
                this.warehouseList = newVal

            },
            deep: true,
            immediate: true
        },
        'createdInfo.warehouseId': {
            handler(newVal, oldVal) {
                if (newVal && newVal !== oldVal) {
                    this.getMaterialList();
                }
            },
            deep: true,
            immediate: true
        }
    },
    created() {
        this.getChangeList();
    },
    methods: {
        chooseTime(e) {
            this.params.startTime = dayjs(e[0]).format("YYYY-MM-DD");
            this.params.endTime = dayjs(e[1]).format("YYYY-MM-DD");
        },
        typeChange(e) {
           this.createdInfo.orderId = null
            let params = {
                pageNumber: 1,
                pageSize: 10000000,
                type:'web'
            }
            if (e == 1) {
                this.$api.saleSaleList(params).then(res => {
                    this.orderList= res.rows;
                })
            } else if (e == 2) {
                this.$api.procureProcureList(params).then(res => {
                    this.orderList= res.rows;
                })
            } else if (e == 3) {
                this.$api.checkCheckList(params).then(res => {
                    this.orderList= res.rows;
                })

            } else if (e == 4) {
                this.$api.damageList(params).then(res => {
                    this.orderList= res.rows;
                })
            }

        },

        getChangeList() {
            this.loading = true
            this.$api.changeChangeList({
                pageSize: this.changeList.pageSize,
                pageNumber: this.changeList.pageNumber,
                changeName: this.params.name,
                startTime: this.params.startTime,
                endTime: this.params.endTime,
                warehouseId: this.params.warehouseId,
                changeType:this.params.changeTypeId,
                addType:'change'
            }).then(res => {
                this.loading = false;
                this.changeList.count = res.count;
                res.rows.map(el => {
                    el.changeDetailList.map(k => {
                        k.totalPrice = Decimal(k.price).mul(Decimal(k.count)).toNumber();
                        // el.changeVouchers = el.changeVouchers.split(',');
                        // el.changeVouchersList = [];
                        // el.changeVouchers.map(k => {
                        //     el.changeVouchersList.push(this.$imgHost + k);

                        // })
                    })
                })
                this.changeList.list = res.rows;
            })
        },
        getImageUrl(e) {
            this.createdInfo.changeInVouchers = e;
        },
        getMaterialList() {
            this.$api.inventoryInventoryList({ pageSize: 100000, pageNumber: 1, warehouseId: this.createdInfo.warehouseId }).then(res => {
                res.rows.map(el => {
                    el.count = 0
                })
                this.materialList = res.rows;
            })
        },
        addChange() {
            this.dialogVisible = true;
        },
        handleChangeSizeChange(e) {
            this.changeList.pageSize = e;
            this.getChangeList();
        },
        handleChangeCurrentChange(e) {
            this.changeList.pageNumber = e;
            this.getChangeList();
        },
        handleClose() {
            this.dialogVisible = false;
            this.createdInfo.time = '';
            this.createdInfo.reason = '';
            this.createdInfo.remark = '';
            this.createdInfo.name = '';
            this.createdInfo.warehouseId = ''
            this.createdInfo.changeInVouchers = ''
            this.materialList = [];
        },
        updateStatus(type, info) {
            if (info.changeStatus !== 0) {
                this.$message.error('当前库存变更单已处理!');
                return;
            }

            this.$alert(`修改ID为:${info.changeId}库存变更单状态`, '提示', {
                confirmButtonText: '确定',
                callback: (res) => {
                    if (res === 'confirm') {
                        this.$api.changeUpdateStatus(
                            {
                                type: type,
                                changeType:'change',
                                changeId: info.changeId,
                                warehouseId: info.warehouseId
                            }
                        ).then(res => {
                            this.getChangeList();
                        })
                    }
                }
            });
        },
        searchGetChangeList(){
            this.changeList.pageNumber = 1;
            this.getChangeList();
        },
        addChangeConfirm() {
            let list = [];
            this.materialList.map(el => {
                if (el.count !== 0 && el.count !== '') {
                    el.materialName = el.material.materialName;
                    el.price = el.material.price;
                    el.salePrice = el.material.salePrice;
                    list = list.concat(el)
                }
            })
            // if (list.length == 0) {
            //     this.$message.error('请添加库存变更材料!');
            //     return
            // }
            // for (let i in this.createdInfo) {
            //     if (this.createdInfo[i] == '') {
            //         this.$message.error('请输入库存变更单信息!');
            //         return
            //     }
            // }
            this.createdInfo.time = dayjs(this.createdInfo.time).format("YYYY-MM-DD");
            this.$api.changeChangeAdd({
                changeDetailList: list,
                changeTime: this.createdInfo.time,
                reason: this.createdInfo.reason,
                remark: this.createdInfo.remark,
                changeName: this.createdInfo.name,
                warehouseId: this.createdInfo.warehouseId,
                changeInVouchers: this.createdInfo.changeInVouchers,
                addType:'change' ,// 库存变更记录
                changeType:this.createdInfo.changeTypeId,
                targetId:this.createdInfo.orderId
            }).then(res => {
                this.createdInfo.time = '';
                this.createdInfo.reason = '';
                this.createdInfo.remark = '';
                this.createdInfo.name = '';
                this.createdInfo.warehouseId = ''
                this.createdInfo.changeInVouchers = ''
                this.materialList = [];
                this.createdInfo.changeTypeId=''
                this.getChangeList();
                this.dialogVisible = false;
            })
        }

    },
};
</script>

<style lang="less" scoped>
.search {
    display: flex;
    align-items: center;
}

.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.mainTable {
    margin: 10px 0;
}

.flex {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 10px;
}

.default /deep/ .el-button {
    border-color: #ff6a00;
    background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
    color: white;
    border-color: #f59a59;
    background-color: #f59a59;
}

/deep/ .el-button:hover {
    color: black;
    border-color: #DCDFE6;
    background-color: white;
}

span /deep/ .el-button:nth-child(2) {
    border-color: #ff6a00;
    background-color: #ff6a00;
}

span /deep/ .el-button:nth-child(2):hover {
    color: white;
    border-color: #f59a59;
    background-color: #f59a59;
}

.createInfo {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 20px
}

.createInfo>div>div:nth-child(1) {
    margin-bottom: 10px;
}
/deep/ .el-input__inner:hover {
    border-color: #ff6a00 !important;
}

/deep/ .el-input__inner:focus {
    border-color: #ff6a00 !important;
}

/deep/ .selected {
    color: #ff6a00 !important;
}

/deep/ .active {
    color: #ff6a00 !important;
}

/deep/ .selected {
    color: #ff6a00 !important;
}

/deep/ .el-loading-text {
    color: #ff6a00 !important;
}

/deep/ .el-icon-loading {
    color: #ff6a00 !important;
}
</style>
